<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label{
    /*width: 130px;*/
    text-align: left;
  }

  .weui-select {
    height: auto;
    line-height: normal;
  }
  *{
    list-style:none;
  }
  /*body{*/

  /*}*/
  .weui-cell_select {
    padding: 10px 15px;
  }
  #acts span {
    font-size: 14px;
  }
  input.time {
    border: none;
    font-size: 16px;
    padding-left: 10px;
  }

  .itit {
    font-size: 12px;
    margin-bottom: 5px;
    text-align: left;
    padding-left: 20px;
  }

  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }
  .weui_uploader_files {
    list-style: none;
  }
  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }
  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }
  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }
  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }
  .weui_uploader_bd {
    overflow: hidden;
  }
  .addcheckRrd >>> .weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }
  .weui-cell.fir {
    border-top: 0;
  }
  .weui_uploader_input_wrp.inrow {
    width: 30px;
    height: 30px;
    margin: 0;
  }
  .weui_uploader_input_wrp:before {
    height: 19.5px;
  }
  .weui_uploader_input_wrp:after {
    width: 19.5px;
  }
  .weui-uploader_file.inrow {
    margin: 0;
    width: 40px;
  }
</style>
<template>
  <div class="addcheckRrd">
    <div style="height: 50px; line-height: 50px; background: #f7f7f7; text-align: center; font-size: 16px; border-bottom: 1px solid #bdbbbc; position: relative">
      录入田检记录
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">所属部门</label></div>
            <div class="weui-cell__bd">
              <input type="text" class="weui-input" name="entity.department" :value="order.department" readonly />
              <input type="hidden" class="weui-input" name="entity.departid" :value="order.departmentguid" />
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">种植户</label></div>
            <div class="weui-cell__bd">
              <input type="text" class="weui-input" name="entity.farmername" :value="order.farmer" readonly />
              <input type="hidden" class="weui-input" name="entity.farmerid" :value="order.farmerid" />
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">地块</label></div>
            <div class="weui-cell__bd">
              <input type="text" class="weui-input" name="entity.arealandname" :value="arealand.aName" readonly />
              <input type="hidden" name="entity.arealandid" :value="arealand.guid" />
<!--              <select class="weui-select" v-model="arealand" style="padding-left: 0;">-->
<!--                <option value="">请选择地块</option>-->
<!--                <option v-for="(item, index) in arealands" :key="item.guid" :value="item">{{item.aName}} {{item.AForests}}亩</option>-->
<!--              </select>-->
              <p style="font-size: 12px;text-align: left;margin-right: 10px">{{arealand.AAddress}} {{arealand.ADtaddress}}</p>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">订单号</label></div>
            <div class="weui-cell__bd">
              <input type="text" class="weui-input" name="entity.ordercode" :value="order.code" readonly />
              <input type="hidden" class="weui-input" name="entity.orderid" :value="order.guid" />
            </div>
          </div>
          <div class="weui-cell weui-cell_select">
            <div class="weui-cell__hd"><label class="weui-label">田检项</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" name="entity.plckname" :value="plck.name" />
              <input type="hidden" name="entity.plckkid" :value="plck.guid" />
              <select class="weui-select specif" v-model="plck">
                <option value="">请选择田检项</option>
                <option v-for="(item, index) in plcks" :key="item.guid" :value="item">{{item.name}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">图片上传</label></div>
            <div class="weui-cell__ft">
              <div class="weui_uploader_bd"><ul class="weui_uploader_files"></ul><div class="weui_uploader_input_wrp inrow"><input type="button" id="selectImage"  class="weui_uploader_input" ></div></div>
            </div>
            <ul class="weui_uploader_files" id="images1" style="font-size: 0; margin-left: 5px;">
              <li class="weui-uploader_file inrow" v-for="(img, index) in images1.serverId" :id="img"  @click=del(img,1) ><img :src="images1.srcStr[index]" width="30"/></li>
            </ul>
          </div>
        </div>
          <template v-for="(ii, outIndex) in items">
            <input type="hidden" class="weui-input" :name="'items[' + packIndex(outIndex) + '].plckitemid'" :value="ii.tit.guid" />
            <input type="hidden" class="weui-input" :name="'items[' + packIndex(outIndex) + '].plckitemname'" :value="ii.tit.name" />
            <input type="hidden" class="weui-input" :name="'items[' + packIndex(outIndex) + '].plckcode'" :value="ii.tit.code" />
            <input type="hidden" class="weui-input" :name="'items[' + packIndex(outIndex) + '].plckresult'" value="" />
            <p class="itit">{{ii.tit.name}}</p>
            <div class="cellgroup">
            <div class="weui-cell" v-for="(item, index) in ii.list">
              <div class="weui-cell__hd"><label class="weui-label">{{item.name}}{{item.name.indexOf('率') > -1 ? '(%)' : ''}}</label></div>
              <div class="weui-cell__bd">
                  <input type="hidden" class="weui-input" :name="'items[' + (index + packIndex(outIndex) + 1) + '].plckitemid'" :value="item.guid" />
                  <input type="hidden" class="weui-input" :name="'items[' + (index + packIndex(outIndex) + 1) + '].plckitemname'" :value="item.name" />
                  <input type="hidden" class="weui-input" :name="'items[' + (index + packIndex(outIndex) + 1) + '].plckcode'" :value="item.code" />
                  <input v-if="item.name.indexOf('率') > -1" type="number" class="weui-input" :class="{ 'reqHolder': item.required == 1 }" :labeltext="item.name" :name="'items[' + (index + packIndex(outIndex) + 1) + '].plckresult'" />
                  <textarea v-else class="weui-textarea" :class="{ 'reqHolder': item.required == 1 }" :labeltext="item.name" :name="'items[' + (index + packIndex(outIndex) + 1) + '].plckresult'" rows="2"></textarea>
              </div>
            </div>
          </div>
      </template>
        <div class="weui-btn-area">
          <a class="weui-btn weui-btn_primary halfbtn subbtn"  href="javascript:" @click="send">提交</a>
          <a class="weui-btn weui-btn_primary halfbtn"  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
  import wx from 'weixin-js-sdk';
  export default {
    data () {
      return {
        id: '',
        plcks: [],
        plck: '',
        order: '',
        arealands: [],
        arealand: '',
        items: [],
        itemLen: 0,
        latitude: '',
        longitude: '',
        existPlcks: [],
        images1: {
          serverId: [],
          srcStr: [],
        },
      }
    },
    created () {
      this.id = this.$route.query.id;
      this.arealand = this.$route.query.arealand;
      this.existPlcks = this.$route.query.existPlcks;

      this.getBaseJsInfo();
      this.getArealands();
      this.getPlcks();
    },
    mounted() {},
    watch: {
      plck: function(val) {
        this.getCheckItems(val.guid);
      }
    },
    methods: {
      packIndex: function(index) {
        let no = 0;
        for (let i=0; i<index; i++) {
          no += this.items[i].list.length + 1;
        }
        return no;
      },
      packItems: function(items) {
        let ldata = [];
        items.forEach((item, index, self) => {
            let idata = {};
            if (item.code.length == 3) {
              idata.tit = item;
              idata.list = self.filter(ii => {
                return ii.code.length == 6 && ii.code.substr(0, 3) == item.code;
              })
              ldata.push(idata);
            }
        })
        return ldata;
      },
      getBaseJsInfo: async function() {
        let params = '';
        await this.axios({
          method: 'get',
          url: '/farmer/Pcrecord!getBaseJsInfo.action',
          params: {url: location.href}
        }).then((response) => {
          if (response.data.params != undefined) {
            params = response.data.params;

            //配置微信公众号参数
            this.wxConfig(response.data.params);
            //上传
            this.wxUoloadImage(this);
          }
        });
        //配置微信公众号参数
        await this.wxConfig(params);
        this.getLoaction();
      },
      wxConfig: async function(wxParams) {
        await wx.config({
          debug: false,            // 开启调试模式,调用的所有api的返回值会在客户端this.toastText出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: wxParams.appid,    // 必填，公众号的唯一标识
          timestamp: wxParams.timestamp,  // 必填，生成签名的时间戳
          nonceStr: wxParams.nonceStr, // 必填，生成签名的随机串
          signature: wxParams.signature,// 必填，签名
          jsApiList: ['getLocation', 'chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表
        });
      },
      getLoaction: function() {
        let that = this;
        wx.getLocation({
          type: 'wgs84',
          success: function ( res ) {
            that.latitude = res.latitude;
            that.longitude = res.longitude;
          },
          fail: function ( res ) {
            console.log('fail res:', res)
          }
        })
      },
      wxUoloadImage: function(that) {
        let cthis = this;
        //wx.ready(function(){
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        document.querySelector('#selectImage').onclick = function () {
          wx.chooseImage({
            success: function (res) {
              $(function(){
                $.each( res.localIds, function(i, n){
                  wx.uploadImage({
                    localId: n,
                    isShowProgressTips: 1,
                    success: function (res) {
                      if (that.checkCore() == 'ios') {
                        wx.getLocalImgData({
                          localId: n, // 图片的localID
                          success: function (res2) {
                            cthis.$nextTick(function () {
                              cthis.images1.srcStr.push(res2.localData);
                            })
                          }
                        });
                      } else {
                        cthis.$nextTick(function () {
                          cthis.images1.srcStr.push(n);
                        })
                      }

                      cthis.images1.serverId.push(res.serverId);
                    },
                    fail: function (res) {
                      $.alert(JSON.stringify(res));
                    }
                  });
                });
              });
            }
          });
        };
        //});

      },
      del: function (id, index){
        let cthis = this;
        $.actions({
          actions: [{
            text: "删除",
            onClick: function() {
              $.confirm("确定删除?", function() {
                //点击确认后的回调函数
                //删掉id
                var ids = cthis['images' + index].serverId;
                var a =  ids.indexOf(id);
                cthis.$nextTick(function () {
                  cthis['images' + index].serverId.splice(a,1);
                  cthis['images' + index].srcStr.splice(a,1);
                })
              }, function() {
                //点击取消后的回调函数
              });
            }
          }
          ]
        });
      },
      checkCore:function() {
        var u = navigator.userAgent;
        //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;//g
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);   //ios终端
        if (isIOS) {
          return 'ios';
        } else  {
          return 'android';
        }
      },
      getOrder: async function(id) {
        await this.axios({
          method: 'get',
          url: '/farmer/Farmerorder!detail.action',
          params: {'entity.guid': id}
        }).then((response) => {
          if (response.data.msg == "success") {
            this.order = response.data.farmerorder;
          } else {
            this.toastText("获取订单数据失败");
          }

        })
      },
      getArealands: async function () {
        await this.getOrder(this.id);
        this.axios({
          method: 'get',
          url: '/harvest/Procurementcontract!getArealand.action',
          params: {userid: this.order.farmerid}
        }).then(response => {
          if (response.data.msg == 'success') {
            this.arealands = response.data.arealands;
          } else {
            this.toastText('获取地块数据失败')
          }
        });
      },
      getPlcks: function() {
        $.showLoading("加载中");
        this.axios({
          method: 'get',
          url: '/farmer/Plantcheck!viewAll.action',
          params: {}
        }).then((response) => {
          if (response.data.msg == 'success') {
            this.plcks = response.data.result.filter(item => {
              return this.existPlcks.indexOf(item.guid) == -1;
            });
            this.plck = this.plcks[0] || '';
          } else {
            this.toastError("系统错误");
          }
          $.hideLoading();
        })
      },
      getCheckItems: function(id) {
        this.axios({
          method: 'get',
          url: '/farmer/Plantcheckitems!findByPlant.action',
          params: {guid: id}
        }).then((response) => {
          if (response.data.msg == 'success') {
            this.items = this.packItems(response.data.result);
            this.itemLen = this.packItems(response.data.result).length;
            console.log('itemLen:', this.itemLen)
          } else {
            this.toastError("系统错误");
          }

        })
      },
      send: function() {
        let that = this;

        if(!checkSubmit(this)){
          return;
        }
        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = this.serialize2Obj($("#formid").serializeArray());
        postData['entity.latitude'] = this.latitude;
        postData['entity.longitude'] = this.longitude;
        postData.imgids = this.images1.serverId.join(',');

        this.axios({
          method: 'post',
          url: '/farmer/Pcrecord!save.action',
          params: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if(response.data.msg == "success"){
            this.toastText('操作成功!');
            this.$router.push({name: 'CheckRecord', query: {id: this.id}});
          }else {
            this.toastError('系统错误!');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });

      },
    }
  }
  /**
   * 提交之前的校验
   */
  function checkSubmit(that){
    if(that.plck == ''){
      that.toastText('请选择田检项');
      return false;
    }
    let reqHolderEle = document.getElementsByClassName('reqHolder');
    if (reqHolderEle.length > 0) {
      for (let index=0; index<reqHolderEle.length; index++) {
        if (reqHolderEle[index].value == '') {
          that.toastText(`请输入${reqHolderEle[index].getAttribute('labeltext')}`);
          return false;
        }
      }
    }
    return true;
  }

</script>
